package com.blog.controller;

import com.blog.pojo.Articles;
import com.blog.pojo.Comment;
import com.blog.pojo.User;
import com.blog.service.ArticleService;
import com.blog.service.CommentService;
import com.blog.service.UserService;
import com.blog.service.impl.ArticleServiceImpl;
import com.blog.service.impl.CommentServiceImpl;
import com.blog.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/commentServlet")
public class CommentServlet extends BaseServlet {

    private CommentService commentService = new CommentServiceImpl();
    private UserService userService = new UserServiceImpl();
    private ArticleService articleService = new ArticleServiceImpl();
    //添加
    public String addComment(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取参数
        String articleId = request.getParameter("articleId");
        String content =request.getParameter("content");
        //登录验证
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            request.setAttribute("msg", "请先登录");
            return "forward:/login.jsp";
        }

        //获取用户id
        int userId = user.getId();
        int articleIdInt = Integer.parseInt(articleId);

            Articles articles= articleService.findById(articleIdInt);
        Integer userId1 = articles.getUserId();

        Comment comment = new Comment();
        comment.setArticleId(articleIdInt);
        comment.setUserId(userId);
        comment.setContent(content);
        boolean add = commentService.addComment(comment);
        if (add) {
            //经验值增加5
            boolean b = userService.addExperience(userId1, 5);
            if (!b) {
                request.setAttribute("msg", "经验值增加失败");
                return "forward:/error.jsp";
            }
//            int experiencePoints = userService.findExperience(userId1);
//            request.setAttribute("experience", experience);
            response.sendRedirect(request.getContextPath() + "/articleServlet?method=findByTitle&id=" + articleId+"");
            return null;
        }else {
            request.setAttribute("msg", "添加失败");
            return "forward:/error.jsp";
        }
    }

    // 删除
    public String deleteComment(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取参数
        String id = request.getParameter("id");
        // 登录验证
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            request.setAttribute("msg", "请先登录");
            return "forward:/login.jsp";
        }
        int idInt = Integer.parseInt(id);
        Comment comment = commentService.findById(idInt);

        if (comment == null) {
            request.setAttribute("msg", "评论不存在");
            return "forward:/error.jsp";
        }
        //获取这个评论的作者在文章表的信息
        Articles articles= articleService.findById(comment.getArticleId());
      //定义两个布尔值，判断是发表评论的人（isCommentOwner）还是文章的作者（isArticleAuthor）
        boolean isCommentOwner = comment.getUserId() == user.getId();
        boolean isArticleAuthor = articles.getUserId() == user.getId();
        Integer userId1 = articles.getUserId();

          //不合符其中一个就无权限，必须要符合两种情况其中的一种才有权限去删除评论
        if (!isCommentOwner && !isArticleAuthor) {
            request.setAttribute("msg", "无权限删除该评论");
            return "forward:/error.jsp";
        }

        boolean delete = commentService.deleteComment(idInt);
        if (delete) {
            //经验值减少5
            boolean b = userService.reduceExperience(userId1, 5);
            if (!b) {
                request.setAttribute("msg", "经验值减少失败");
                return "forward:/error.jsp";
            }
            int experiencePoints = userService.findExperience(userId1);
            request.setAttribute("experiencePoints", experiencePoints);

//            return "forward:/articleDetail.jsp";
            // 删除成功后返回 JSON,这里不可以return，因为会导致这说明后端已成功删除，但返回的 JSON 格式或字段与前端预期不一致，
            // 导致前端 if (data.success) 判断为 false，从而弹出“删除失败”。
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.write("{\"success\":true}");
            out.flush();
            return null;   // 不再 forward
        } else {
            request.setAttribute("msg", "删除失败！");
            return "forward:/error.jsp";
                }

        }



    //修改
    public String updateComment(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取参数
        String id = request.getParameter("id");
        String articleId = request.getParameter("articleId");
        String userId = request.getParameter("userId");
        String content =request.getParameter("content");
        //登录验证
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            request.setAttribute("msg", "请先登录");
            return "forward:/login.jsp";
        }
        //调用service
        int idInt = Integer.parseInt(id);
        //查找对应id的评论
        Comment comment = commentService.findById(idInt);
        if (comment == null) {
            request.setAttribute("msg", "评论不存在");
            return "forward:/error.jsp";
        }
        //查找文章id
        Articles articles= articleService.findById(comment.getArticleId());
        //两种权限
        boolean isCommentOwner = comment.getUserId() == user.getId();
        //判断
        if(!isCommentOwner){
            request.setAttribute("msg", "无权限修改该评论");
            return "forward:/error.jsp";
        }

        comment.setId(idInt);
        comment.setArticleId(Integer.parseInt(articleId));
        comment.setUserId(Integer.parseInt(userId));
        comment.setContent(content);
        boolean update = commentService.updateComment(comment);
        if (update) {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.write("{\"success\":true}");
            out.flush();
            return null;   // 不再 forward
        } else {
            request.setAttribute("msg", "修改失败");
            return "forward:/error.jsp";
        }



    }



    //查询--全部
    public String findAll(HttpServletRequest request, HttpServletResponse response){
        List<Comment> commentList = commentService.findAll();
        request.setAttribute("comment", commentList);
        return null;
    }
    //     //查询--作者
    public String findByAuthor(HttpServletRequest request, HttpServletResponse response){
        String author = request.getParameter("author");
        List<Comment> byAuthor = commentService.findByAuthor(author);
        request.setAttribute("byAuthor", byAuthor);
        return "forward:/comment/findByAuthor";
    }
    //     //查询--标题
    public String findByTitle(HttpServletRequest request, HttpServletResponse response){
        String title = request.getParameter("title");
        List<Comment> byTitle = commentService.findByTitle(title);
        request.setAttribute("byTitle", byTitle);
        return "forward:/comment/findByTitle";
    }
    //查询--id
    public String findById(HttpServletRequest request, HttpServletResponse response){
        String id = request.getParameter("id");
        Comment comment = commentService.findById(Integer.parseInt(id));
        request.setAttribute("comment", comment);
        return null;
    }

    //查询--文章id
    public String findByArticleId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取参数
        String articleId = request.getParameter("articleId");
        //2.登录验证
        HttpSession session=request.getSession();
        User user=(User) session.getAttribute("user");
        if(user==null){
            request.setAttribute("msg","请先登录");
        }
        int articleIdInt=Integer.parseInt(articleId);
        // 3. 获取文章
        Articles article = articleService.findById(articleIdInt);
        request.setAttribute("article", article);
        //4.调用service
        List<Comment> commentList = commentService.findByArticleId(articleIdInt);
        // 5. 设置评论用户名
        for (Comment c : commentList) {
            User u = userService.findById(c.getUserId());
            c.setUserName(u.getUsername());
        }
        request.setAttribute("commentList", commentList);
        return "forward:/commentServlet?method=findByArticleId&articleId=" + articleId;

    }
}


